﻿/// <reference path="../typings/angularjs/angular.d.ts"/>

class QuizCtrl {

    answered: boolean;
    title: string;
    options: any;
    correctAnswer: boolean;
    working: boolean;

    constructor(private $scope: ng.IScope, private $http: ng.IHttpService) {

        this.answered = false;
        this.title = "loading question...";
        this.options = [];
        this.correctAnswer = false;
        this.working = false;
    }

    public answer() {
        return this.correctAnswer ? 'correct' : 'incorrect';
    }

    public nextQuestion() {
        this.working = true;

        this.answered = false;
        this.title = "loading question...";
        this.options = [];

        // functionではなくラムダ式を渡すと、thisがこのオブジェクトを指す
        // functionにすると、おそらく、thisがそのfunctionを指してしまう
        this.$http.get("/api/trivia").success((data: any, status:number, headers:ng.IHttpHeadersGetter, config:ng.IRequestConfig) => {
            this.options = data.options;
            this.title = data.title;
            this.answered = false;
            this.working = false;
        }).error((data, status, headers, config) => {
                this.title = "Oops... something went wrong";
                this.working = false;
            });
    }

    public sendAnswer(option: any){
        this.working = true;
        this.answered = true;

        this.$http.post('/api/trivia', { 'questionId': option.questionId, 'optionId': option.id }).success((data, status, headers, config) => {
            // dataの型がbooleanだったり、stringだったりするので、toStringする
            this.correctAnswer = (data === true);
            this.working = false;
        }).error((data, status, headers, config) => {
                this.title = "Oops... something went wrong";
                this.working = false;
            });
    }
}

angular.module('QuizApp', []).controller('QuizCtrl', ['$scope', '$http', QuizCtrl]);